package com.shengqi.xinnongren.work.ui.home.activities;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.goods.activities.GoodsDetailsActivity;
import com.shengqi.xinnongren.work.ui.goods.activities.ShoppingCartActivity;
import com.shengqi.xinnongren.work.ui.home.adapter.CommonGoodsAdapter;
import com.shengqi.xinnongren.work.ui.home.model.GoodsBean;
import com.shengqi.xinnongren.work.ui.home.presenter.SpecialSalePresenter;
import com.shengqi.xinnongren.work.ui.home.view.SpecialSaleView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SpecialSaleActivity extends BaseMvpActivity<SpecialSaleView, SpecialSalePresenter> implements SpecialSaleView {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.fl_cart_container)
    FrameLayout mFlCartContainer;
    @BindView(R.id.tv_cart_num)
    TextView mTvCartNum;

    private List<GoodsBean> mList;
    private CommonGoodsAdapter mAdapter;
    private BroadcastReceiver mReceiver;
    private int pageIndex = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                getCartNum();
            }
        };
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(mReceiver, new IntentFilter(MainActivity.ACTION_REFRESH_CART_NUM));
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_special_sale;
    }

    @Override
    protected void initView() {
        mList = new ArrayList<>();
        mAdapter = new CommonGoodsAdapter(this, mList);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        mRecyclerView.setAdapter(mAdapter);
        mRefreshLayout.setOnRefreshListener(refreshLayout -> refreshData()).setOnLoadMoreListener(refreshLayout -> mPresenter.getList(pageIndex));
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dy > 10) {
                    mFlCartContainer.animate().alpha(0f).translationY(mFlCartContainer.getHeight()).start();
                    mFlCartContainer.setEnabled(false);
                }
                if (dy < -10) {
                    mFlCartContainer.animate().alpha(1f).translationY(0).start();
                    mFlCartContainer.setEnabled(true);
                }
            }
        });
    }

    /**
     * 购物车
     */
    @OnClick(R.id.fl_cart_container)
    void fl_cart_container() {
        if (Global.checkLogin(this)) {
            startActivity(new Intent(this, ShoppingCartActivity.class));
        }
    }

    private void refreshData() {
        pageIndex = 0;
        mList.clear();
        mPresenter.getList(pageIndex);
    }

    private void getCartNum() {
        if (UserManager.getInstance().isLogin())
            mPresenter.getShoppingCartNum();
    }

    @Override
    protected void initData() {
        mPresenter.getList(pageIndex);
        getCartNum();
    }

    @Override
    public void onGetShoppingCartNum(int num) {
        if (num > 0)
            mTvCartNum.setVisibility(View.VISIBLE);
        else
            mTvCartNum.setVisibility(View.INVISIBLE);
        mTvCartNum.setText(String.valueOf(num));
    }

    @Override
    protected SpecialSalePresenter createPresenter() {
        return new SpecialSalePresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        mRefreshLayout.finishRefresh().finishLoadMore();
        hideLoadingDialog();
    }

    @Override
    public void showSpecialSaleGoodsList(List<GoodsBean> data) {
        mRefreshLayout.finishRefresh().finishLoadMore();
        if (data.size() > 0) {
            pageIndex++;
        }
        mList.addAll(data);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showRequestFailed(String message) {
        mRefreshLayout.finishRefresh().finishLoadMore();
        ToastHelper.getInstance(this).showWarn(message);
    }


    class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.Holder> {

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(getLayoutInflater().inflate(R.layout.item_recommend_goods_list, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull SpecialSaleActivity.GoodsAdapter.Holder holder, int position) {

            GoodsBean goodsBean = mList.get(position);
            if (goodsBean.getIsNew() == 1)
                holder.item_isNew.setVisibility(View.VISIBLE);
            else
                holder.item_isNew.setVisibility(View.GONE);

            ImageUtils.showImage(SpecialSaleActivity.this, goodsBean.getDeputyPic(), holder.item_pic);
            holder.item_name.setText(goodsBean.getName());
            if (TextUtils.isEmpty(goodsBean.getOriginPlace()))
                holder.tv_original_place.setVisibility(View.GONE);
            else
                holder.tv_original_place.setVisibility(View.VISIBLE);
            holder.tv_original_place.setText(goodsBean.getOriginPlace());
            holder.item_discount_price.setText(goodsBean.getUnitPrice());
            holder.item_unit.setText("/" + goodsBean.getPriceName());


            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(SpecialSaleActivity.this, goodsBean.getID()));
            holder.item_car.setOnClickListener(v -> Global.showSpecificationDialog(SpecialSaleActivity.this, goodsBean.getID()));
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_isNew)
            FrameLayout item_isNew;
            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_name)
            TextView item_name;
            @BindView(R.id.tv_original_place)
            TextView tv_original_place;
            @BindView(R.id.item_discount_price)
            TextView item_discount_price;
            @BindView(R.id.item_unit)
            TextView item_unit;
            @BindView(R.id.item_car)
            ImageView item_car;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }
}
